package com.abcd.download

import com.facebook.react.bridge.*
import com.facebook.react.module.annotations.ReactModule
import com.facebook.react.modules.core.DeviceEventManagerModule

/**
 * 回调方法使用
 * Created by mazaiting on 2018/6/6.
 */
@ReactModule(name = "DownloadAndroid")
class DownloadModule(private val reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {

    override fun getName(): String {
        return "DownloadAndroid"
    }

    @ReactMethod
    fun download(errorCallback: Callback, loadCallback: Callback) {
        // 回调
        testNum(errorCallback, loadCallback)
    }

    /**
     * 下载回调
     * @param errorCallback 错误回调
     * @param loadCallback 成功回调
     */
    private fun testNum(errorCallback: Callback, loadCallback: Callback) {
        try {
            loadCallback.invoke(100)
        } catch (e: Exception) {
            errorCallback.invoke(e.message)
        }
    }

    /**
     * 为JS发送事件
     */
    @ReactMethod
    fun downloadFile() {
        try {
            for (i in 0..99) {
                val params = Arguments.createMap()
                params.putInt("progress", i)
                sendEvent(reactContext, "download", params)
                Thread.sleep(10)
            }
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
    }

    /**
     * 发送事件
     * @param reactContext 设备上下文
     * @param eventName 事件名称
     * @param params 参数
     */
    private fun sendEvent(reactContext: ReactApplicationContext, eventName: String, params: WritableMap?) {
        reactContext
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
                .emit(eventName, params)
    }

}